const http = require('http')
const util = require('util')

http.get('http://127.0.0.1:3000/data.json', res => {
  const { statusCode } = res
  const contentType = res.headers['content-type']
  let error
  let data = ''

  if (statusCode !== 200) {
    error = new Error(`Request failed\n.Status Code: ${statusCode}`)
  } else if (!/^application\/json/.test(contentType)) {
    error = new Error(`Invalid content-type.\nExpected application/json, but received ${contentType}`)
  }

  if (error) {
    console.error(error.message)
    res.resume()
    return
  }

  console.log(statusCode, contentType)
  res.on('data', chunk => {
    data += chunk
  })
  res.on('end', () => {
    console.log(util.inspect(data))
  })
})
